package com.yangxk.upload.provider.disk;

import com.yangxk.upload.provider.UploadProvider;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.FilenameUtils;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.Calendar;
import java.util.UUID;

public class DiskUploadProvider implements UploadProvider {

    private String diskDir;

    private String resourceMappingPrefix;

    public String upload(String filename, InputStream in) {

        if (filename == null || "".equals(filename))
            throw new RuntimeException("上传文件名称不能为空");
        if (in == null)
            throw new RuntimeException("上传文件输入流不能为空");

        try {
            String targetDir = getTargetDir();
            String targetFilename = getTargetFilename(filename);

            File dir = new File(targetDir);
            if (!dir.exists())
                dir.mkdirs();

            File file = new File(targetDir, targetFilename);
            FileUtils.copyInputStreamToFile(in, file);

            return getRelativePath(file.getAbsolutePath());
        } catch (IOException e) {
            e.printStackTrace();
            throw new RuntimeException("文件上传失败");
        }
    }

    private String getTargetDir() {
        Calendar calendar = Calendar.getInstance();
        int year = calendar.get(Calendar.YEAR);
        int month = calendar.get(Calendar.MONTH) + 1;

        String result = diskDir + File.separator + resourceMappingPrefix + File.separator + year + File.separator + month;

        diskDir = FilenameUtils.separatorsToSystem(FilenameUtils.normalize(diskDir));
        result = FilenameUtils.separatorsToSystem(FilenameUtils.normalize(result));

        return result;
    }

    private String getTargetFilename(String filename) {
        String suffix = getFileSuffix(filename);
        // 文件没有扩展名
        if (suffix == null || "".equals(suffix)) {
            return uuid();
        }

        return uuid() + "." + suffix;
    }

    private String getFileSuffix(String filename) {
        return FilenameUtils.getExtension(filename);
    }

    private String uuid() {
        return UUID.randomUUID().toString().replace("-", "");
    }

    private String getRelativePath(String fullPath) {
        return fullPath.substring(diskDir.length());
    }


    public void setDiskDir(String diskDir) {
        this.diskDir = diskDir;
    }

    public void setResourceMappingPrefix(String resourceMappingPrefix) {
        this.resourceMappingPrefix = resourceMappingPrefix;
    }

}
